package me.project.offer;

import java.util.Arrays;

/**
 * 根据二叉树的前序遍历和中序遍历的结果，重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
 *
 * preorder = [3,9,20,15,7]
 * inorder =  [9,3,15,20,7]
 *
 * Note:
 * 前序遍历的第一个值为根节点的值，使用这个值将中序遍历结果分成两部分，
 * 左部分为树的左子树中序遍历结果，右部分为树的右子树中序遍历的结果。
 * @author Mcdull
 * @date 2018-6-29
 */
public class Solution07 {
    public static void main(String[] args) {
        Solution07 solution07 = new Solution07();
        int[] pre ={3,9,20,15,7};
        int[] in = {9,3,15,20,7};
        TreeNode root = solution07.reConstructBinaryTree(pre,in);


    }
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre.length == 0 || in.length == 0)
            return null;
        TreeNode node = new TreeNode(pre[0]);
        for (int i = 0; i < pre.length; i++) {
            if (pre[0] == in[i]) {
                node.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
                node.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
                break;
            }
        }
        return node;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
